package com.xiaodong.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaodong.reggie.dto.DishDto;
import com.xiaodong.reggie.entity.Dish;
import com.xiaodong.reggie.entity.DishFlavor;
import com.xiaodong.reggie.mapper.DishMapper;
import com.xiaodong.reggie.service.DishFlavorService;
import com.xiaodong.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    //进行菜品和口味的添加
    @Override
    @Transactional
    public void saveByDto(DishDto dishDto) {

        //添加菜品
        this.save(dishDto);

        //获取菜品id
        Long dishId = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();

        //将菜品id添加到flavors集合中
        flavors = flavors.stream().map((item) -> {

            item.setDishId(dishId);

            return item;

        }).collect(Collectors.toList());

        //添加菜品id
        dishFlavorService.saveBatch(flavors);

    }

    //查询菜品和口味的数据
    @Override
    public DishDto getDishAndFlavor(Long id) {

        //获取菜品数据
        Dish byId = this.getById(id);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId, dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId, byId.getId());

        List<DishFlavor> one = dishFlavorService.list(queryWrapper);

        dishDto.setFlavors(one);

        return dishDto;
    }

    //修改菜品和口味的数据
    @Override
    @Transactional
    public void updateDishAndFlavor(DishDto dishDto) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish, "flavors,categoryName,copies");

        this.updateById(dish);

        List<DishFlavor> flavors = dishDto.getFlavors();

        //删除口味表里的记录

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //将菜品id添加到flavors集合中
        flavors = flavors.stream().map((item) -> {

            item.setDishId(dishDto.getId());

            return item;

        }).collect(Collectors.toList());

        //添加口味
        dishFlavorService.saveBatch(flavors);

    }
}
